package com.bankcomm.voice;

import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.utils.Utils;
import com.xioai.framework.XIAOIApplication;
import com.xioai.framework.api.JsonUtils;
import com.xioai.framework.api.jsonbean.Call;
import com.xioai.framework.api.jsonbean.Plugin;
import com.xioai.framework.api.jsonbean.Response;
import com.xioai.framework.voicecontrol.VcSession;
import com.xioai.framework.voicecontrol.VoiceControl;

/**
 * call 指令跳转
 * @author liujia (liujia9234@126.com)
 * @data @2012-4-10
 * @version 1.0
 * <ul>
 * 		<li>1.0 创建</li>
 * </ul>
 */
public class CallForward {
	
	public static final String TAG = "CallForward";
	private Activity activity = null;
	public static String []sms = new String[2];
	HttpManager hmg_ ;
	String  robotUrl_ ;
	String ROBOT_reply ;
	public void pushServerData(Activity activity, Response response){
        this.activity=activity;
		Call call = response.getCall();
		if(call != null){
			List<String> args = response.getCall().getArgs();
			if("setprop".equals(call.getName())){
				if(args != null && args.size() >= 2){
					String value = args.get(1);
					callStoreKeyValue(args.get(0),value);
				}
			}else if("sendback".equals(call.getName())){
				VoiceControl.getInstance().askData(JsonUtils.replaceContent(args.get(0)));
			}else if("phone".equals(call.getName())){//调电话
				if(args != null && args.size() > 0 && !"".equals(args.get(0).trim())){
					hintAndDelayedDirectTel("", args.get(0));
				}else{
					hintAndDelayedDirectTel("", "");
				}
			}else if("sms".equals(call.getName())){//发短信
				if(args != null && args.size() > 0 && !"".equals(args.get(0).trim())){
					if(args.size() > 1){
						if(sms[0].equals(args.get(1))){
							callSMS(args.get(0), sms[1]);
						}else{
							callSMS(args.get(0), "");
						}
						
					}else{
						callSMS(args.get(0), "");
					}
				}else{
					callSMS("", "");
				}
			}else if("bankcomm".equals(call.getName())){
				if(args != null && args.size() >= 1){
					//设置LPMid中的isRobotJump为true，判断是否由小i跳转
//					Bundle inBundle = new Bundle();
//					inBundle.putString ("SpeakerBody", args.get(0));
//					startActivity(activity, "com.bankcomm.SpeakerToDetail", inBundle, true);
					String respondsfromi = args.get(0);
		            if(respondsfromi != null){
		            	StringBuilder sBuilder = new StringBuilder();
		            	sBuilder.append(ConfigManager.ROBOT_I_URL);
		            	
		            	String[] keyValues = respondsfromi.split("&");
		            	for(String str : keyValues) {
		            		String[] sItem = str.split("=");
		            		if(sItem.length == 2) {
		            			sBuilder.append(sItem[0]);
		            			sBuilder.append("=");
		            			sBuilder.append(Utils.escapeURIComponent(sItem[1]));
		            			sBuilder.append("&");
		            		}
		            	}
		            	// delete the last '&'.
		        		if (sBuilder.length() > 0 && sBuilder.charAt(sBuilder.length() - 1) == '&') {
		        			sBuilder.deleteCharAt(sBuilder.length() - 1);
		        		}
		            	robotUrl_ = sBuilder.toString();
		            	sBuilder.delete(0, sBuilder.length());
		            	Utils.printOutToConsole("ROBOT_I_URL---------------------->"+robotUrl_);
		            }
		            xiaoIgotoEMP();
				}
			}
		}
		Plugin plugin = response.getPlugin();
		if (plugin != null){
			if (plugin.getName() != null ){
				if("sms".equals(plugin.getName())){
					sms[0]= plugin.getId();
					sms[1] = plugin.getArgs().size() > 1?plugin.getArgs().get(1):"";
				}
			}
		}
	}

	public void xiaoIgotoEMP(){
		WaitDialog waitdg = new WaitDialog();
		waitdg.addFgTask(activity, null, 0, 0, 0, new WaitDialog.Task(0) {
			@Override
			public void run(WaitDialog dlg) throws Exception {
				// TODO Auto-generated method stub
				hmg_ = LPMid.getInstance().hm_;
				String body = null ;
				ROBOT_reply = (String) hmg_.sendPostRequest(robotUrl_, body, null, null, null);
				ROBOT_reply = AESCipher.decrypt(ROBOT_reply, AESCipher.serverKey_, AESCipher.serverIv_);
				Utils.printOutToConsole("+++++ ROBOT_reply:\n" + ROBOT_reply);
			}
			@Override
			public void onSuccess(WaitDialog dlg) {
				// TODO Auto-generated method stub
				super.onSuccess(dlg);
				activity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.putExtra("reply", ROBOT_reply) ;
						intent.setAction("com.bankcomm.SpeakerToDetail");
						activity.startActivity(intent) ;
						activity.finish();
					}
				});
			}
			@Override
			public void onFailure(WaitDialog dlg) {
				// TODO Auto-generated method stub
				super.onFailure(dlg);
				((VoiceFrameActivity)activity).handleException(getErrMsg());
			}
			
		});
}
	/**
	 * 拨打电话
	 * @param name
	 * @param phoneNum
	 * @param activity 
	 */	
	public void hintAndDelayedDirectTel(String name,final String phoneNum){
		try {
			if(phoneNum == null || phoneNum.length() == 0){
				callTelDial(phoneNum);
			}else{
				callTel(phoneNum);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	



	/**
	 * 启动一个新的Activity
	 * @param action
	 * @param bundle
	 */
	public void startActivity(Activity activity, String action,Bundle bundle,boolean finishCurr){
		try {
			VcSession.getInstance().onCreateSession();
			/*
			toastActivityInfo(activity.getBaseContext(), action, bundle, finishCurr);
			action = BOCDetailView.class.getName();
			Intent intent = new Intent(activity.getApplicationContext(),Class.forName(action));
			*/
			Intent intent = new Intent();
			intent.setAction(action);
			intent.putExtras(bundle);
			activity.startActivity(intent);
			if(finishCurr){
				activity.finish();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Utils.LogD(TAG+"启动Action["+action+"]发生异常",e.toString());
		}
		
	}
	
	/**
	 * 存储临时数据
	 * @param key
	 * @param value
	 */
	private void callStoreKeyValue(String key,String value){
		SharedPreferences shared = XIAOIApplication.getInstance().getSharedPreferencesByKeyData(key);
		if(shared != null){
			Editor editShare = shared.edit();
			editShare.putString(key, value);
			editShare.commit();
		}
	}
	
	public void toastActivityInfo(Context context,String action,Bundle bundle,boolean finishCurr){
		StringBuilder sb = new StringBuilder();
		sb.append("ACTION:"+action+"\n");
		sb.append("请求参数:\n");
		Set<String> keys = bundle.keySet();
		sb.append("==总共"+keys.size()+"个参数==\n");
		sb.append(bundle+"\n");
		sb.append("===============\n");
		Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
	}
	
	/**
	 * 调用电话（直接拨号）
	 */
	public void callTel(String phoneNum) {
		try {
			if(phoneNum.length() == 3){
				callTelDial(phoneNum);
			}else{
				Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNum));
				if(activity != null){
					activity.startActivity(intent);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 调用电话（打开拨号界面）
	 */
	public void callTelDial(String phoneNum){
		
		try {
			Intent intent = null;
			if(phoneNum == null || phoneNum.length() == 0){
				intent = new Intent(Intent.ACTION_DIAL);
			}else{
				intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phoneNum));
			}
			if(activity != null){
				activity.startActivity(intent);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 短信发送(调用短信界面)
	 * @param phoneNum
	 * @param message
	 */
	public void callSMS(String phoneNum,String message) {
		try {
			Uri smsToUri = Uri.parse("smsto:"+phoneNum);
			Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );
			mIntent.putExtra("sms_body",message);
			if(activity != null){
				activity.startActivity( mIntent );
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
}
